//
//  SpecialPageViewController.m
//  MoGuRadio
//
//  Created by dlios on 15/6/3.
//  Copyright (c) 2015年 mogu.com 蘑菇科技. All rights reserved.
//

// ViewControllers
#import "SpecialPageViewController.h"
#import "CollectPageViewController.h"
#import "MyRadioViewController.h"

// 自定义类
#import "Special.h"
#import "Detail.h"
#import "BaseModel.h"
#import "DLBView.h"
#import "MushRoom.h"
#import "AllDetail.h"

// 第三方
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "UIButton+InitButton.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "UIView+ChangeFrame.h"
#import "DataBaseHandler.h"

// 自定义cell
#import "SpecialTableViewCell.h"

// 表视图的重用池宏
#define DATATABLEVIEW_REUSE @"DataTableViewReuseIdentifier"

@interface SpecialPageViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, MBProgressHUDDelegate> {
    
    MBProgressHUD *hud;
    NSInteger num;
}

// 接收数据的数组
@property (nonatomic, retain) NSMutableArray *specialArr;
@property (nonatomic, retain) NSDictionary *specialDic;
@property (nonatomic, retain) NSMutableArray *detailArr;
// 用来存放上拉加载出来的数据
@property (nonatomic, retain) NSMutableArray *mainArr;

@property (nonatomic, retain) UIScrollView *mainScrollView;// 主滚动
@property (nonatomic, retain) UIView *mainView;// 上半部分的UIView
@property (nonatomic, retain) UIView *sectionView;// 下半部分表视图分区UIView
@property (nonatomic, retain) UITableView *dataTableView;// 显示数据的表视图

// 专题页面数据
@property (nonatomic, retain) UIImageView *picLeftImage;// 左边主播图片
@property (nonatomic, retain) UILabel *hostNameLabel;// 主播名字
@property (nonatomic, retain) UIImageView *foucsImage;// 关注的小图标
@property (nonatomic, retain) UIImageView *listenImage;// 收听小图标
@property (nonatomic, retain) UILabel *foucsLabel;// 关注人数
@property (nonatomic, retain) UILabel *listenLabel;// 收听人数

@property (nonatomic, retain) UIButton *shareButton;// 分享按钮
@property (nonatomic, retain) UIButton *foucsButton;// 关注按钮
@property (nonatomic, retain) UIButton *listenAllButton; // 收听全部按钮
@property (nonatomic, retain) UILabel *descLabel;// 电台介绍

@property (nonatomic, assign, getter=isLabelExtend) BOOL labelExtend;

@end

@implementation SpecialPageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor colorWithRed:0.88 green:0.90 blue:0.738 alpha:0.4];
    self.mainArr = [NSMutableArray array];
    [self setUpSubViews];
    [self dataHandler];
    [self.dataTableView addFooterWithTarget:self action:@selector(DetailHandler)];
    [self.dataTableView footerBeginRefreshing];
    
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    view.tag = 10001;
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [self MBProgressHUD];
    
}


- (void)setUpSubViews
{

    self.mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT / 2.5)];
    self.mainView.backgroundColor = [UIColor colorWithRed:0.88 green:0.90 blue:0.738 alpha:0.4];
    
    self.dataTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.dataTableView.delegate = self;
    self.dataTableView.dataSource = self;
//    self.dataTableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
    self.dataTableView.scrollEnabled = YES;
    self.dataTableView.tableHeaderView = self.mainView;
    [self.view addSubview:self.dataTableView];
    
    [self.dataTableView registerClass:[SpecialTableViewCell class] forCellReuseIdentifier:DATATABLEVIEW_REUSE];
    
    [_dataTableView release];
    [_mainView release];
    
    [self setUp];
}


// 创建专题页面上半部分的全部控件
- (void)setUp
{
    
    self.picLeftImage = [[UIImageView alloc] initWithFrame:CGRectMake(20 * kXWidth, 17 * kYHeight, VIEW_WIDTH / 3.3, VIEW_HEIGHT / 6)];
    self.picLeftImage.backgroundColor = [UIColor blueColor];
    self.picLeftImage.layer.cornerRadius = 15;
    self.picLeftImage.layer.masksToBounds = YES;
    NSString *picImage = self.pic;
    NSURL *url = [NSURL URLWithString:picImage];
    [self.picLeftImage setImageWithURL:url];
    [self.mainView addSubview:self.picLeftImage];
    [_picLeftImage release];
    
    
    self.hostNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 2.5, VIEW_HEIGHT / 38, VIEW_WIDTH / 2 + 40 * kXWidth, VIEW_HEIGHT / 18)];
    self.hostNameLabel.backgroundColor = [UIColor clearColor];
    self.hostNameLabel.numberOfLines = 0;
    self.hostNameLabel.tintColor = [UIColor whiteColor];
    self.hostNameLabel.font = [UIFont boldSystemFontOfSize:18];
    self.hostNameLabel.text = [NSString stringWithFormat:@"主播: %@", self.hostName];
    NSLog(@"--%@", self.hostNameLabel.text);
    [self.mainView addSubview:self.hostNameLabel];
    [_hostNameLabel release];
    
    
    self.foucsImage = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 2.5, VIEW_HEIGHT / 10, VIEW_WIDTH / 30, VIEW_HEIGHT / 50)];
    self.foucsImage.image = [UIImage imageNamed:@"like.png"];
    [self.mainView addSubview:self.foucsImage];
    [_foucsImage release];
    
    self.foucsLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 2.2, VIEW_HEIGHT / 10.3, VIEW_WIDTH / 2, VIEW_HEIGHT / 38)];
    self.foucsLabel.text = [BaseModel foucsChangeStringValue:self.foucsNum];
//    self.foucsLabel.backgroundColor = [UIColor greenColor];
    self.foucsLabel.font = [UIFont boldSystemFontOfSize:13];
    [self.mainView addSubview:self.foucsLabel];
    [_foucsLabel release];

    
    self.listenImage = [[UIImageView alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 2.5, VIEW_HEIGHT / 7, VIEW_WIDTH / 25, VIEW_HEIGHT / 45)];
    self.listenImage.image = [UIImage imageNamed:@"listen.png"];
    [self.mainView addSubview:self.listenImage];
    [_listenImage release];
    
    self.listenLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 2.2, VIEW_HEIGHT / 7.1, VIEW_WIDTH / 2, VIEW_HEIGHT / 38)];
    self.listenLabel.text = [BaseModel listenChangeStringValue:self.listenNum];
    //    self.foucsLabel.backgroundColor = [UIColor greenColor];
    self.listenLabel.font = [UIFont boldSystemFontOfSize:13];
    [self.mainView addSubview:self.listenLabel];
    [_listenLabel release];

    
    self.shareButton = [UIButton buttonWithTitle:@"分享" frame:CGRectMake(VIEW_WIDTH / 17, VIEW_HEIGHT / 4.5, VIEW_WIDTH / 4, VIEW_HEIGHT / 20) target:self action:@selector(shareWeiBoButtonAcion:)];
    self.shareButton.backgroundColor = [UIColor colorWithRed:0.097 green:0.6701 blue:0.4134 alpha:1.0];
    [self.shareButton.layer setMasksToBounds:YES];
    [self.shareButton.layer setCornerRadius:5.0];
//    [self.shareButton.layer setBorderWidth:0.12];
    [self.mainView addSubview:self.shareButton];
    
    
    self.foucsButton = [UIButton buttonWithTitle:@"关注" frame:CGRectMake(VIEW_WIDTH / 2.7, VIEW_HEIGHT / 4.5, VIEW_WIDTH / 4, VIEW_HEIGHT / 20) target:self action:@selector(foucsButtonAction:)];
    self.foucsButton.backgroundColor = [UIColor colorWithRed:0.097 green:0.6701 blue:0.4134 alpha:1.0];
    [self.foucsButton.layer setMasksToBounds:YES];
    [self.foucsButton.layer setCornerRadius:5.0];
//    [self.foucsButton.layer setBorderWidth:0.12];
    [self.mainView addSubview:self.foucsButton];
    
    
    
    self.listenAllButton = [UIButton buttonWithTitle:@"收听节目" frame:CGRectMake(VIEW_WIDTH / 1.2 - 50, VIEW_HEIGHT / 4.5, VIEW_WIDTH / 4, VIEW_HEIGHT / 20) target:self action:@selector(listenAllButtonAction:)];
    self.listenAllButton.backgroundColor = [UIColor colorWithRed:0.097 green:0.6701 blue:0.4134 alpha:1.0];
    [self.listenAllButton.layer setMasksToBounds:YES];
    [self.listenAllButton.layer setCornerRadius:5.0];
//    [self.listenAllButton.layer setBorderWidth:0.12];
    [self.mainView addSubview:self.listenAllButton];
    
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    self.descLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 15, VIEW_HEIGHT / 3.2, VIEW_WIDTH - 30, VIEW_HEIGHT / 15)];
    self.descLabel.text = [NSString stringWithFormat:@"电台介绍: %@", self.descRadio];
    self.descLabel.userInteractionEnabled = YES;
    self.descLabel.numberOfLines = 3;
    self.descLabel.font = [UIFont boldSystemFontOfSize:13];
//    [self.descLabel addGestureRecognizer:tap];
    [self.mainView addSubview:self.descLabel];

//    [tap release];
}



// 数据加载条
- (void)MBProgressHUD
{
    // 加载图MBProgressHUD
    UIView *view = [self.view viewWithTag:10001];
    
    // 方式1: 直接在view上show
    hud = [[MBProgressHUD showHUDAddedTo:view animated:YES] retain];
    hud.delegate = self;
    // 常用设置
    // 小矩形的背景颜色
    hud.color = [UIColor grayColor];
    //显示的文字
    hud.labelText = @"玩命加载中......";
    // 是否有遮罩
    hud.dimBackground = YES;
    hud.removeFromSuperViewOnHide = YES;
//    hud.mode = MBProgressHUDModeIndeterminate;
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    
    [hud showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
    
}

- (void)myProgressTask
{
    float p = 0.0f;
    while (p < 1.0f) {
        p += 0.01;
        hud.progress = p;
        usleep(50000);
    }
}


//- (void)tapAction:(UITapGestureRecognizer *)tap
//{
//    
//    if (self.isLabelExtend) {
//        
//        [self.descLabel changeHeight:65];
//        
//    } else {
//        
//        CGRect rect = [self.descRadio boundingRectWithSize:CGSizeMake(VIEW_WIDTH - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
//        [self.descLabel changeHeight:rect.size.height];
//    }
//    
//    self.labelExtend = !self.isLabelExtend;
//    [self resetAllFrame];
//    
//}


//- (void)resetAllFrame
//{
//    [self.dataTableView changeHeight:self.dataTableView.contentSize.height + 30];
//    [self.dataTableView changeFrameY:_descLabel.frameY + _descLabel.height];
//    [self.mainView changeHeight:VIEW_HEIGHT / 2.5];
//    [self.mainView changeHeight:_descLabel.frameY + _descLabel.height];
//}



- (void)foucsButtonAction:(UIButton *)button
{
    DataBaseHandler *handler = [DataBaseHandler shareInstance];

    MushRoom *mushRoom = [[MushRoom alloc] init];
    mushRoom.rid = self.rid;
    mushRoom.pic = self.pic;
    mushRoom.desLabelText = self.descRadio;
    mushRoom.listenLabelText = self.listenNum;
    mushRoom.focusLabelText = self.foucsNum;
    mushRoom.titleLabelText = self.titleLabel;
    mushRoom.hostNameText = self.hostName;
    
    [handler insertMushRoom:mushRoom];
    
    NSLog(@"沙盒地址: %@",  NSHomeDirectory());
}


- (void)listenAllButtonAction:(UIButton *)button
{
    MyRadioViewController *myRadioVC = [MyRadioViewController shareInstance];
    
    myRadioVC.playImage = [[self.mainArr objectAtIndex:_listenAllButton.tag] objectForKey:@"albumPic"];
    myRadioVC.rname = [[self.mainArr objectAtIndex:_listenAllButton.tag] objectForKey:@"audioName"];
    myRadioVC.mp3Url = [[self.mainArr objectAtIndex:_listenAllButton.tag] objectForKey:@"mp3PlayUrl"];
    
    [self.navigationController pushViewController:myRadioVC animated:YES];
    
    NSLog(@"收听全部按钮");
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"123";
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    DLBView *dlbView = [[DLBView alloc] init];
    dlbView.backgroundColor = [UIColor colorWithRed:0.097 green:0.6701 blue:0.4134 alpha:1.0];
    dlbView.lineImageView.image = [UIImage imageNamed:@"line.png"];
    NSString *countNum = [self.specialDic objectForKey:@"countNum"];
    dlbView.sectionLabel.text = [NSString stringWithFormat:@"共%@期", countNum];
    
    [dlbView.reverseButton addTarget:self action:@selector(reverseButton:) forControlEvents:UIControlEventTouchUpInside];
    [dlbView.reverseButton setTitle:@"✿2015最火✿网络电台✿" forState:UIControlStateNormal];
    
    dlbView.reverseButton.tintColor = [UIColor whiteColor];
    [dlbView.shareButton addTarget:self action:@selector(shareWeiBoButtonAcion:) forControlEvents:UIControlEventTouchUpInside];
    
    return dlbView;
}

- (void)reverseButton:(UIButton *)button
{
    NSLog(@"倒序");
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mainArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return LBVIEW_HEIGHT1 / 5.5 * kYHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.f * kYHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SpecialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DATATABLEVIEW_REUSE];
    
    self.title = self.titleLabel;

    NSInteger order = [[[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"orderNum"] integerValue];
    NSString *title = [[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"audioName"];
    
    cell.titleLabel.text = [NSString stringWithFormat:@"%ld期: %@", (long)order, title];
    cell.listenImageView.image = [UIImage imageNamed:@"listen.png"];
    cell.likeImageView.image = [UIImage imageNamed:@"liked.png"];
    cell.updateTimeImageView.image = [UIImage imageNamed:@"clound.png"];
    
    cell.listenNumLabel.text = [[[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"listenNum"] description];
    
    cell.likedNumLabel.text = [[[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"likedNum"] description];
    
    cell.updateTimeLabel.text = [[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"updateTime"];
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyRadioViewController *myRadioVC = [MyRadioViewController shareInstance];
    
    myRadioVC.playImage = [[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"albumPic"];
    myRadioVC.rname = [[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"audioName"];
    myRadioVC.mp3Url = [[self.mainArr objectAtIndex:indexPath.row] objectForKey:@"mp3PlayUrl"];
    
    _listenAllButton.tag = indexPath.row;
    
    [self.navigationController pushViewController:myRadioVC animated:YES];
    
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor colorWithRed:0.88 green:0.90 blue:0.738 alpha:0.4];
}


- (void)viewWillAppear:(BOOL)animated
{
//    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)dataHandler
{
    
    NSString *dataStr = [NSString stringWithFormat:@"http://api.kaolafm.com/api/v3.1/resource/radioinfo?rid=%@&rtype=0&operator=1&timestamp=1433753996&resolution=640*960&installid=0000SZ6c&version=3.5.1&appid=0&devicetype=1&page=200003&sign=F317B886396CA8621454351A56755FF7&sessionid=992F82693201480582EB2A98D28835E9&udid=22D16F7F86EBC08060D1A4AE78E40A34&network=1&channel=appstore", self.rid];
    
    dataStr = [dataStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    
    [manger GET:dataStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        self.specialDic = [responseObject objectForKey:@"result"];
        [self.dataTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"错误信息是==%@", error);
        
    }];
    
}


- (void)DetailHandler
{
    num++;
    NSLog(@"====请求数 = %ld", (long)num);
   NSString *dataStr = [NSString stringWithFormat:@"http://api.kaolafm.com/api/v3.1/album/audiolist?rid=%@&pagesize=10&sorttype=1&pagenum=%ld&operator=1&timestamp=1434186178&resolution=640*960&installid=0000SZ6c&version=3.5.1&appid=0&devicetype=1&page=200004&sign=F317B886396CA8621454351A56755FF7&sessionid=FF2E366900864C3CA34A7C58837B9905&udid=22D16F7F86EBC08060D1A4AE78E40A34&network=1&channel=appstore", self.rid, (long)num];
    dataStr = [dataStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    
    [manger GET:dataStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        self.detailArr = [[responseObject objectForKey:@"result"] objectForKey:@"dataList"];
//         NSInteger countNum = [[self.specialDic objectForKey:@"countNum"] integerValue];
        
        for (NSMutableDictionary *dic in self.detailArr) {
            
//            if (self.mainArr.count < countNum) { }
                [self.mainArr addObject:dic];
                [self.dataTableView reloadData];
        }
    
        [self.dataTableView footerEndRefreshing];
        hud.delegate = nil;
        [hud hide:YES];
        UIView *view = [self.view viewWithTag:10001];
        [view removeFromSuperview];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"错误信息是==%@", error);
        [hud hide:YES];
        
        // 打印错误信息
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请检查网络" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [self.view addSubview:alertView];
        [alertView show];
        [alertView release];
        
    }];
    
}


- (void)dealloc
{
    hud.delegate = nil;
    [_rid release];
    [_titleLabel release];
    [_sectionView release];
    [_likedNum release];
    [_upTime release];
    [_foucsNum release];
    [_listenNum release];
    [_foucsImage release];
    [_foucsLabel release];
    [_listenImage release];
    [_listenLabel release];
    [_descLabel release];
    [_hostName release];
    [_mainView release];
    [_pic release];
    [_detailArr release];
    [_specialArr release];
    [_specialDic release];
    [_mainScrollView release];
    [_dataTableView release];
    [_picLeftImage release];
    [_hostNameLabel release];
    [super dealloc];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
